<template>
  <div class="login-page">
    <div class="page-main">
      <!-- 注册相关表单 -->
      <el-form
        :model="loginData"
        class="login-form"
        label-width="100px"
        :rules="loginDataRules"
        ref="loginForm"
        size="large"
        v-if="isRegister"
      >
        <el-form-item>
          <h3>欢迎注册</h3>
          <!--          <div class="register_tabs">-->
          <!--            <el-tabs v-model="activeName" class="demo-tabs">-->
          <!--              <el-tab-pane-->
          <!--                label="用户名注册"-->
          <!--                name="username"-->
          <!--              ></el-tab-pane>-->
          <!--              <el-tab-pane-->
          <!--                label="邮箱注册"-->
          <!--                name="email"-->
          <!--              ></el-tab-pane>-->
          <!--            </el-tabs>-->
          <!--          </div>-->
        </el-form-item>
        <div>
          <el-form-item prop="username">
            <template #label>
              <span>用户名:</span>
            </template>
            <el-input
              v-model="loginData.username"
              placeholder="请输入用户名"
            ></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <template #label>
              <span>密码:</span>
            </template>
            <el-input
              ref="passwordInput"
              v-model="loginData.password"
              type="password"
              show-password
              placeholder="请输入密码"
            ></el-input>
          </el-form-item>
        </div>

        <div class="email_register_box">
          <el-form-item prop="emailAddress">
            <template #label>
              <span>邮箱:</span>
            </template>
            <el-input
              v-model="loginData.emailAddress"
              placeholder="请输入邮箱"
            ></el-input>
          </el-form-item>
          <div class="get_email_code">
            <!--            <el-button-->
            <!--              type="primary"-->
            <!--              style="width: 100px"-->
            <!--              :disabled="isButtonDisabled"-->
            <!--              @click="getEmailRegisterCode('register')"-->
            <!--            >-->
            <!--              {{-->
            <!--                isButtonDisabled-->
            <!--                  ? countdown + '秒后重发'-->
            <!--                  : '获取验证码'-->
            <!--              }}-->
            <!--            </el-button>-->
          </div>
          <el-form-item prop="code">
            <template #label>
              <span>验证码:</span>
            </template>
            <el-input
              ref="passwordInput"
              v-model="loginData.code"
              type="text"
              placeholder="请输入验证码"
              style="width: 60%"
            ></el-input>
            <el-button
              type="primary"
              style="width: 35%; margin-left: 5%"
              :disabled="isButtonDisabled"
              @click="getEmailRegisterCode('login')"
            >
              {{
                isButtonDisabled
                  ? countdown + '秒后重发'
                  : '获取验证码'
              }}
            </el-button>
          </el-form-item>
        </div>

        <div class="register_box">
          <el-link
            type="info"
            :underline="false"
            @click="isRegister = false"
          >
            去登录
          </el-link>
        </div>
        <el-form-item>
          <el-button
            @click="register"
            class="button"
            type="primary"
            auto-insert-space
          >
            马上注册
          </el-button>
        </el-form-item>
        <!--        <el-form-item class="flex">-->
        <!--          -->
        <!--        </el-form-item>-->
      </el-form>

      <!-- 登录相关表单 -->
      <el-form
        ref="loginForm"
        class="login-form"
        label-width="100px"
        :model="loginData"
        :rules="loginDataRules"
        size="large"
        v-else
      >
        <el-form-item>
          <h3>欢迎登录</h3>
          <div class="register_tabs">
            <el-tabs
              v-model="loginActiveTab"
              class="demo-tabs"
            >
              <el-tab-pane
                label="用户名登录"
                name="userNameLogin"
              ></el-tab-pane>
              <el-tab-pane
                label="邮箱登录"
                name="emailLogin"
              ></el-tab-pane>
            </el-tabs>
          </div>
        </el-form-item>

        <div v-if="loginActiveTab === 'userNameLogin'">
          <el-form-item prop="username">
            <template #label>
              <span>用户名:</span>
            </template>
            <el-input
              placeholder="请输入用户名"
              v-model="loginData.username"
              clearable
              autocomplete="on"
            ></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <template #label>
              <span>密码:</span>
            </template>
            <el-input
              placeholder="请输入密码"
              v-model="loginData.password"
              show-password
              clearable
            ></el-input>
          </el-form-item>
        </div>

        <div
          class="email_login"
          v-if="loginActiveTab === 'emailLogin'"
        >
          <el-form-item prop="emailAddress">
            <template #label>
              <span>邮箱:</span>
            </template>
            <el-input
              placeholder="请输入邮箱"
              v-model="loginData.emailAddress"
              clearable
              autocomplete="on"
            ></el-input>
          </el-form-item>

          <div class="get_email_code_login">
            <!--            <el-button-->
            <!--              type="primary"-->
            <!--              style="width: 100px"-->
            <!--              :disabled="isButtonDisabled"-->
            <!--              @click="getEmailRegisterCode('login')"-->
            <!--            >-->
            <!--              {{-->
            <!--                isButtonDisabled-->
            <!--                  ? countdown + '秒后重发'-->
            <!--                  : '获取验证码'-->
            <!--              }}-->
            <!--            </el-button>-->
          </div>

          <el-form-item prop="code">
            <template #label>
              <span>验证码:</span>
            </template>
            <el-input
              placeholder="请输入验证码"
              v-model="loginData.code"
              show-password
              clearable
              style="width: 60%"
            ></el-input>
            <el-button
              type="primary"
              style="width: 35%; margin-left: 5%"
              :disabled="isButtonDisabled"
              @click="getEmailRegisterCode('login')"
            >
              {{
                isButtonDisabled
                  ? countdown + '秒后重发'
                  : '获取验证码'
              }}
            </el-button>
          </el-form-item>
        </div>

        <!--        <div class="register_box">-->
        <!--          <el-link-->
        <!--            type="info"-->
        <!--            :underline="false"-->
        <!--            @click="isRegister = true"-->
        <!--          >-->
        <!--            去注册-->
        <!--          </el-link>-->
        <!--        </div>-->

        <el-form-item>
          <el-button type="primary" @click="login"
            >立即登录
          </el-button>
        </el-form-item>
      </el-form>

      <div
        class="login-bg"
        :style="{ width: `100%`, height: `100vh` }"
      >
        <svg
          width="100%"
          height="100%"
          xmlns="http://www.w3.org/2000/svg"
          viewBox="0 0 1920 1080"
          preserveAspectRatio="none"
        >
          <g
            transform="
            rotate(0 960 540)
            translate(-0 -0)
            scale(1)
          "
          >
            <rect
              width="100%"
              height="100%"
              fill="rgb(145, 145, 145)"
            ></rect>
            <g transform="translate(0, 0)">
              <path
                fill="rgb(97, 97, 97)"
                fill-opacity="1"
                d="M0,352.943L45.714,350.075C91.429,347.207,182.857,341.471,274.286,340.581C365.714,339.692,457.143,343.65,548.571,344.095C640,344.54,731.429,341.472,822.857,303.183C914.286,264.894,1005.714,191.383,1097.143,185.175C1188.571,178.967,1280,240.06,1371.429,221.336C1462.857,202.612,1554.286,104.069,1645.714,98.48C1737.143,92.892,1828.571,180.258,1874.286,223.941L1920,267.624L1920,1080L1874.286,1080C1828.571,1080,1737.143,1080,1645.714,1080C1554.286,1080,1462.857,1080,1371.429,1080C1280,1080,1188.571,1080,1097.143,1080C1005.714,1080,914.286,1080,822.857,1080C731.429,1080,640,1080,548.571,1080C457.143,1080,365.714,1080,274.286,1080C182.857,1080,91.429,1080,45.714,1080L0,1080Z"
              ></path>
            </g>
            <g transform="translate(0, 360)">
              <path
                fill="rgb(48, 48, 48)"
                fill-opacity="1"
                d="M0,136.093L45.714,117.434C91.429,98.774,182.857,61.455,274.286,80.719C365.714,99.983,457.143,175.829,548.571,189.505C640,203.181,731.429,154.687,822.857,130.414C914.286,106.141,1005.714,106.09,1097.143,141.274C1188.571,176.458,1280,246.877,1371.429,284.697C1462.857,322.517,1554.286,327.739,1645.714,284.675C1737.143,241.611,1828.571,150.263,1874.286,104.589L1920,58.914L1920,720L1874.286,720C1828.571,720,1737.143,720,1645.714,720C1554.286,720,1462.857,720,1371.429,720C1280,720,1188.571,720,1097.143,720C1005.714,720,914.286,720,822.857,720C731.429,720,640,720,548.571,720C457.143,720,365.714,720,274.286,720C182.857,720,91.429,720,45.714,720L0,720Z"
              ></path>
            </g>
            <g transform="translate(0, 720)">
              <path
                fill="rgb(0, 0, 0)"
                fill-opacity="1"
                d="M0,107.121L45.714,134.307C91.429,161.493,182.857,215.866,274.286,254.33C365.714,292.794,457.143,315.35,548.571,300.514C640,285.679,731.429,233.452,822.857,180.313C914.286,127.174,1005.714,73.123,1097.143,43.365C1188.571,13.606,1280,8.141,1371.429,41.079C1462.857,74.017,1554.286,145.358,1645.714,167.782C1737.143,190.206,1828.571,163.713,1874.286,150.467L1920,137.221L1920,360L1874.286,360C1828.571,360,1737.143,360,1645.714,360C1554.286,360,1462.857,360,1371.429,360C1280,360,1188.571,360,1097.143,360C1005.714,360,914.286,360,822.857,360C731.429,360,640,360,548.571,360C457.143,360,365.714,360,274.286,360C182.857,360,91.429,360,45.714,360L0,360Z"
              ></path>
            </g>
          </g>
        </svg>
      </div>
    </div>
  </div>
</template>

<script setup>
// import authApi from '@/api/auth'
// import userApi from  '@/api/user'

import {
  login as Login, // 登录
  regist, // 注册
} from '@/api/loginRegister.js'

import {
  getUserInfo, // 获取当前用户信息
} from '@/api/userMessage.js'

// 获取邮箱验证码
import { getEmailCode } from '@/api/getEmailCode.js'

import { getCurrentInstance, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElLoading } from 'element-plus'

// 存储用户信息pinia仓库
import { useUserStore } from '@/stores/modules/userInfo.js'

const userStore = useUserStore()

const isRegister = ref(false)
const loginForm = ref() // 获取表单实例
const router = useRouter()
const TOKEN_KEY_IN_MEM = 'General_Token'
const TOKEN_EXPIRE_TIME_KEY_IN_MEM = 'tokenExpireTime'
const USER_IN_MEM = 'userInfo'
const { proxy } = getCurrentInstance()
const loginData = ref({
  username: '',
  password: '',
  // repassword: '',
  emailAddress: '',
  code: '',
})
const loginDataRules = {
  username: [
    {
      required: true,
      message: '请输入用户名',
      trigger: 'blur',
    },
    {
      min: 4,
      max: 256,
      message: '用户名必须不少于4个字符',
      trigger: 'blur',
    },
  ],
  password: [
    {
      required: true,
      message: '请输入密码',
      trigger: 'blur',
    },
    {
      pattern: /^\S{6,65535}$/,
      message: '密码必须不少于6个非空字符',
      trigger: 'blur',
    },
  ],
  emailAddress: [
    {
      required: true,
      message: '请输入邮箱',
      trigger: 'blur',
    },
    {
      type: 'email',
      message: '请输入正确的邮箱格式',
      trigger: ['blur'],
    },
  ],
  code: [
    {
      required: true,
      message: '请输入验证码',
      trigger: 'blur',
    },
  ],
}

// 注册
const register = async () => {
  await loginForm.value.validate() // 校验通过，才会执行后面的代码
  // 开启加载
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '注册中...',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  try {
    // 用户名密码注册
    console.log(loginData.value)
    const res = await regist(loginData.value, {
      roleName: 'ADMINISTRATOR',
    })
    console.log(res)
    ElMessage.success('注册成功，请登录')
    // 切换为去登录
    isRegister.value = false
  } catch (err) {
    console.log(err)
    if (err.status === 409) {
      ElMessage.error('用户名已存在')
    } else {
      ElMessage.error('注册失败')
    }
  } finally {
    loadingInstance.close()
  }

  // return

  // authApi
  //   .register(loginData.value)
  //   .then((res) => {
  //     console.log(res)
  //     ElMessage.success('注册成功!')
  //   })
  //   .catch((err) => {
  //     console.warn(err)
  //     ElMessage.error('注册失败!')
  //   })

  // isRegister.value = false;
}

// 注册时获取邮箱验证码
const getEmailRegisterCode = async (occasion) => {
  if (!loginData.value.emailAddress) {
    ElMessage.error('请输入邮箱')
    return
  }

  const isEmail = isValidEmail(loginData.value.emailAddress)
  if (!isEmail) {
    ElMessage.error('邮箱格式不正确')
    return
  }

  const loadingInstance = ElLoading.service({
    lock: true,
    text: '正在发送验证码...',
    background: 'rgba(0, 0, 0, 0.7)',
  })

  try {
    // 调用验证码接口
    const res = await getEmailCode(occasion, {
      emailAddress: loginData.value.emailAddress,
    })
    ElMessage.success('获取验证码成功')
    console.log(res)

    // 成功后启动倒计时
    startCountdown()
  } catch (error) {
    console.log(error)
    ElMessage.error('发送验证码失败')
  } finally {
    loadingInstance.close()
  }
}

// 校验邮箱格式
function isValidEmail(email) {
  const emailRegex =
    /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/
  return emailRegex.test(email)
}

// 控制获取验证码按钮禁用
const isButtonDisabled = ref(false)
// 获取验证码倒计时
const countdown = ref(60)
// 获取验证码倒计时定时器
let timer = null

// 开启获取验证码倒计时
function startCountdown() {
  isButtonDisabled.value = true
  countdown.value = 60

  timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer)
      isButtonDisabled.value = false
    }
  }, 1000)
}

// 登录
const login = async () => {
  await loginForm.value.validate() // 校验通过，才会执行后面的代码
  // 开启加载
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '登录中...',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  try {
    let type =
      loginActiveTab.value === 'userNameLogin'
        ? 'username' // 用户名密码注册
        : 'email' // 邮箱验证码登录

    // 调用登录接口
    const res = await Login(loginData.value, { type })
    // 解构token
    const { token, tokenExpireTime } = res
    // token持久化存储
    localStorage.setItem(
      TOKEN_KEY_IN_MEM,
      'Bearer ' + token,
    )
    localStorage.setItem(
      TOKEN_EXPIRE_TIME_KEY_IN_MEM,
      tokenExpireTime,
    )
    // 将token存储到pinia仓库中
    userStore.setToken('Bearer ' + token)

    // 获取当前用户信息
    const userInfo = await getUserInfo()

    console.log(userInfo)
    // 如果当前账号角色不是管理员，不允许登录
    if (userInfo.role !== 'ADMINISTRATOR') {
      ElMessage.error('无管理员权限，请检查账号')
      // 清除token
      proxy.clearToken()
      return
    }
    userStore.userInfo = userInfo
    // console.log(res)
    localStorage.setItem(
      USER_IN_MEM,
      JSON.stringify(userInfo),
    )
    ElMessage({
      type: 'success',
      message: '登录成功',
    })
    // 登录成功，跳转到收取包裹页面
    router.push({ name: 'Main' })
  } catch (err) {
    console.log(err)
    ElMessage.error('登录失败')
  } finally {
    loadingInstance.close()
  }
  // authApi
  // .login(loginData.value)
  // .then(({ token, tokenExpireTime }) => {
  //   localStorage.setItem(
  //     TOKEN_KEY_IN_MEM,
  //     'Bearer ' + token,
  //   )
  //   localStorage.setItem(
  //     TOKEN_EXPIRE_TIME_KEY_IN_MEM,
  //     tokenExpireTime,
  //   )
  //   // return
  //
  //
  //
  //
  //
  //
  //
  //   .getUserInfo()
  // })
  // .then((res) => {
  //   localStorage.setItem(USER_IN_MEM, JSON.stringify(res))
  //   ElMessage({
  //     message: '登录成功!',
  //     type: 'success',
  //   })
  //   router.push({ name: 'ReceivePackage' })
  // })
  // .catch((err) => {
  //   console.error(err)
  //   ElMessage({
  //     message: '登录失败',
  //     type: 'error',
  //   })
  // })
}

// 登录方式
const loginActiveTab = ref('userNameLogin')

// 注册方式
const activeName = ref('username')

// 切换 登录或注册 时重置表单内容
// 重置 登录方式 或 注册方式
watch(isRegister, () => {
  loginData.value = {
    username: '',
    password: '',
    // repassword: '',
    emailAddress: '',
    code: '',
  }
  loginActiveTab.value = 'userNameLogin'
  activeName.value = 'username'

  // 重置定时器
  isButtonDisabled.value = false
  countdown.value = 60
  timer = null
})

// 切换登录方式时重置对应表单内容
watch(loginActiveTab, () => {
  loginData.value = {
    username: '',
    password: '',
    // repassword: '',
    emailAddress: '',
    code: '',
  }
  // 重置定时器
  isButtonDisabled.value = false
  countdown.value = 60
  timer = null
})

// 切换注册方式时重置对应表单内容
watch(activeName, () => {
  loginData.value = {
    username: '',
    password: '',
    // repassword: '',
    emailAddress: '',
    code: '',
  }
})
</script>

<style scoped lang="scss">
.login-page {
  height: 100vh;
}

.page-main {
  position: relative;
  width: 100%;
  max-height: 100%;
}

.login-form {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  width: 50%;
  max-width: 400px;

  .email_login {
    position: relative;

    .get_email_code_login {
      position: absolute;
      top: -2px;
      right: -110px;
    }
  }
}

.login-bg {
  overflow: hidden;
}

h3 {
  font-size: 28px;
  margin-bottom: 20px;
  margin-left: 28%;
  letter-spacing: 5px;
  color: #fff;
  text-align: center;
}

.el-button {
  width: 100%;
}

.el-form-item span {
  color: #fff;
  font-size: 16px;
}

.register_tabs {
  //width: 100%;
  display: flex;
  justify-content: end;

  :deep(.el-tabs__item) {
    color: #fff;
  }

  margin-bottom: -15px;
}

.register_box {
  display: flex;
  justify-content: end;
  margin-bottom: 10px;
  //padding-right: 5px;
  font-size: 12px;
  color: #409eff;

  .el-link {
    color: #409eff;
  }
}

.email_register_box {
  position: relative;

  .get_email_code {
    position: absolute;
    right: -110px;
    top: 14px;
    display: flex;
    justify-content: end;
    margin-top: -15px;
    margin-bottom: 22px;
  }
}
</style>
